package org.example.batch.service.threadPool;

import java.util.concurrent.*;

/**
 * 自定义线程池
 */
public class CustomThreadPool {

    private static ThreadPoolExecutor createExecutor() {
        int corePoolSize = Runtime.getRuntime().availableProcessors() + 1;
        int maxPoolSize = corePoolSize * 2;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(100);

        // 拒绝策略：由提交线程直接执行（保证可用性）
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();

        return new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                30, TimeUnit.SECONDS,
                workQueue,
                handler
        );
    }

    private static class Holder {
        private static final ThreadPoolExecutor INSTANCE = createExecutor();
    }

    public static void execute(Runnable task) {
        Holder.INSTANCE.execute(task);
    }
}